﻿using System;
using System.Globalization;

namespace Kivensoft.XlsWriter
{
    public class Metadata {

        private string applicationVersion;

        public bool UseColorMRU { get; set; }
        public string Title { get; set; }
        public string Subject { get; set; }
        public string Creator { get; set; }
        public string Keywords { get; set; }
        public string Application { get; set; }
		public string ApplicationVersion {
			get { return applicationVersion; }
			set {
				applicationVersion = value;
				CheckVersion();
			}
		}
        public string Description { get; set; }
        public string Category { get; set; }
        public string ContentStatus { get; set; }
        public string Manager { get; set; }
        public string Company { get; set; }
        public string HyperlinkBase { get; set; }

        public Metadata() {
            UseColorMRU = false;
			Creator = "Kivensoft";
            Application = "XlsxLib";
            Version vi = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            ApplicationVersion = ParseVersion(vi.Major, vi.Minor, vi.Revision, vi.Build);
        }

        public static string ParseVersion(int major, int minor, int build, int revision) {
            if (major < 0 || minor < 0 || build < 0 || revision < 0) {
                throw new FormatException("The format of the passed version is wrong. No negative number allowed.");
            }
            if (major > 99999) {
                throw new FormatException("The major number may not be bigger than 99999. The passed value is " + major.ToString());
            }
            CultureInfo culture = CultureInfo.CreateSpecificCulture("zh-CN");
            string leftPart = major.ToString("G", culture);
            string rightPart = minor.ToString("G", culture) + build.ToString("G", culture) + revision.ToString("G", culture);
            rightPart = rightPart.TrimEnd('0');
            if (rightPart == "") rightPart = "0";
            else {
                if (rightPart.Length > 5)
                    rightPart = rightPart.Substring(0, 5);
            }
            return leftPart + "." + rightPart;
        }

        private void CheckVersion() {
            if (string.IsNullOrEmpty(applicationVersion)) { return; }
            string[] split = applicationVersion.Split('.');
            bool state = true;
            if (split.Length != 2) { state = false; }
            else {
                if (split[1].Length < 1 || split[1].Length > 5) { state = false; }
                if (split[0].Length < 1 || split[0].Length > 5) { state = false; }
            }
            if (state == false) {
                throw new FormatException("The format of the version in the meta data is wrong (" + applicationVersion + "). Should be in the format and a range from '0.0' to '99999.99999'");
            }
        }

    }
}
